﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Think.Lenovo.Com.DataAccess;
using Think.Lenovo.Com.Models;
using System.Data;

namespace Think.Lenovo.Com
{
    public partial class productAdd : System.Web.UI.Page
    {
        Roles roles = new Roles();
        productModel pro = new productModel();
        productInfo proinfo = new productInfo();
        public string rel = string.Empty;
        public string filePath = HttpRuntime.AppDomainAppVirtualPath;
        productClassInfo modelInfo = new productClassInfo();
        protected int ClassKind
        {
            get
            {
                return (int)ViewState["ClassKind"];
            }
            set
            {
                ViewState["ClassKind"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                Bind_Right();
                try
                {
                    if (Int32.Parse(Request.QueryString["id"].ToString()) > 0)
                    {
                        Bind_product(Int32.Parse(Request.QueryString["id"].ToString()));
                        Button1.Text = "更新";
                    }
                }
                catch (Exception ex)
                {
                    // throw;
                }

                this.ClassKind = Convert.ToInt32(Request.QueryString["ClassKind"]);
                BindData();
            }
            
        }

        #region 数据绑定
        private void BindData()
        {
            DataSet ds = modelInfo.GetClassList(this.ClassKind);

            this.ddl_lanmu.Items.Clear();
            this.ddl_lanmu.Items.Add(new ListItem("请选择分类", "0"));
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                int ClassTj = Convert.ToInt32(dr["ClassTj"]);
                string ClassId = dr["ClassId"].ToString().Trim();
                string ClassName = dr["ClassName"].ToString().Trim();

                if (ClassTj == 1)
                {
                    this.ddl_lanmu.Items.Add(new ListItem(ClassName, ClassId));

                }
                else
                {
                    ClassName = "├ " + ClassName;
                    ClassName = StringHelper.StringOfChar(ClassTj - 1, "　") + ClassName;

                    this.ddl_lanmu.Items.Add(new ListItem(ClassName, ClassId));
                }
            }

        }
        #endregion

        ///// <summary>
        ///// 绑定权限
        ///// </summary>
        public void Bind_Right()
        {
            cbl_right.DataSource = roles.GetRoles();
            cbl_right.DataBind();
        }

        public void Bind_product(int id)
        {
            DataSet ds = proinfo.GetProductId(id);

            txt_title.Text = ds.Tables[0].Rows[0][1].ToString();
            editor.Value = ds.Tables[0].Rows[0][4].ToString();
            string[] right = ds.Tables[0].Rows[0][5].ToString().Split(',');

            foreach (string str in right)
            {
                for (int i = 0; i < cbl_right.Items.Count; i++)
                {
                    if (this.cbl_right.Items[i].Value == str)
                    {
                        this.cbl_right.Items[i].Selected = true;
                    }
                }
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (Request.QueryString.Count > 0)
                {
                    Update();
                }
                else
                {
                    Add();
                }
            }
            catch (Exception ex)
            {
                // throw;
            }
        }

        public void Add()
        {

            pro.Title = txt_title.Text;
            pro.Pclass = ddl_lanmu.SelectedValue;
            //pro.Pic = FileUpload1.FileName;
            pro.Content = editor.Value;
            pro.ReleaseTime = DateTime.Now;
            if (FileUpload1.FileName != null)
            {
                UploadImage(FileUpload1);
            }
            pro.Pic = rel;
            //获取选中权限
            foreach (ListItem item in this.cbl_right.Items)
            {
                if (item.Selected == true)
                {
                    pro.Bright += item.Value + ",";
                }
            }

            if (proinfo.Addproduct(pro) > 0)
            {
                Response.Write("<script>alert('添加成功');location.href=location.href;</script>");
            }
        }

        public void Update()
        {
            pro.ID = Int32.Parse(Request.QueryString["id"].ToString());
            pro.Title = txt_title.Text;
            // pro.Pclass = ddl_lanmu.SelectedValue;
           // pro.Pic = FileUpload1.FileName;
            pro.Content = editor.Value;
            pro.ReleaseTime = DateTime.Now;

            if (FileUpload1.FileName != "")
            {
                UploadImage(FileUpload1);
                pro.Pic = rel;
            }
            else
            {
                pro.Pic = lbl_img.Text;
            }

            //获取选中权限
            foreach (ListItem item in this.cbl_right.Items)
            {
                if (item.Selected == true)
                {
                    pro.Bright += item.Value + ",";
                }
            }

            if (proinfo.Updateproduct(pro) > 0)
            {
                Response.Write("<script>alert('更新成功');location.href=location.href;</script>");
            }
        }


        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="fileUpload"></param>
        private void UploadImage(FileUpload fileUpload)
        {
            bool fileOk = false;

            string size = fileUpload.PostedFile.ContentLength.ToString();

            //取得文件的扩展名,并转换成小写
            string fileExtension = System.IO.Path.GetExtension(fileUpload.FileName).ToLower();
            //限定只能上传jpg和gif图片
            string[] allowExtension = { ".jpg", ".gif" };
            //对上传的文件的类型进行一个个匹对
            for (int i = 0; i < allowExtension.Length; i++)
            {
                if (fileExtension == allowExtension[i])
                {
                    fileOk = true;
                    break;
                }
            }
            if (!fileOk)
            {
                Response.Write("<script>alert('文件格式不正确！');location.href=location.href;</script>");
                return;
            }
            //对上传文件的大小进行检测，限定文件最大不超过1M
            if (fileUpload.PostedFile.ContentLength > 3082000)
            {
                fileOk = false;
            }

            if (fileOk)
            {
                try
                {
                    if (System.IO.Directory.Exists(Server.MapPath(filePath)) == false)//如果不存在就创建file文件夹
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(filePath));
                    }
                    String ReName = Guid.NewGuid().ToString();
                    rel = filePath + "upload/" + ReName + fileExtension;
                    fileUpload.PostedFile.SaveAs(Server.MapPath(rel));
                    //hiddenImgUrl.Value = ReName + fileExtension;
                    //Image1.ImageUrl = SysConfiguration.UploadFilesPath + "Registration/" + hiddenImgUrl.Value;
                    //resultlbl.Text ="上传成功";
                }
                catch
                {

                    //resultlbl.Text = "上传失败";
                }
            }
            else
            {
                Response.Write("<script>alert('文件大小超出3M！');location.href=location.href;</script>");
                //JavaScript.Alert("文件大小超出3M！", this.Page);
                //resultlbl.Text = "文件类型或者文件大小超出3M或者文件类型不对";
            }
        }


        #region
        public static class StringHelper
        {
            /// <summary>
            /// 生成指定长度的字符串,即生成strLong个str字符串
            /// </summary>
            /// <param name="strLong">生成的长度</param>
            /// <param name="str">以str生成字符串</param>
            /// <returns></returns>
            public static string StringOfChar(int strLong, string str)
            {
                string ReturnStr = "";
                for (int i = 0; i < strLong; i++)
                {
                    ReturnStr += str;
                }

                return ReturnStr;
            }

            /// <summary>
            /// 生成日期随机码
            /// </summary>
            /// <returns></returns>
            public static string GetRamCode()
            {
                #region
                return DateTime.Now.ToString("yyyyMMddHHmmssffff");
                #endregion
            }
        }
        #endregion
    }
}